package vip.zhenzicheng.nettyadv.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import vip.zhenzicheng.nettyadv.constant.MessageType;
import vip.zhenzicheng.nettyadv.server.asyncpro.AsyncBusyProcess;
import vip.zhenzicheng.nettyadv.server.asyncpro.ITaskProcessor;
import vip.zhenzicheng.nettyadv.util.EncryptUtils;
import vip.zhenzicheng.nettyadv.vo.MsgHeader;
import vip.zhenzicheng.nettyadv.vo.MyMessage;

import java.util.logging.Logger;

/**
 * @author zhenzicheng
 * @date 2022-06-14 09:57
 */
public class ServerBusyHandler extends SimpleChannelInboundHandler<MyMessage> {

  private static final Logger LOG = Logger.getLogger(ServerBusyHandler.class.getSimpleName());
  private ITaskProcessor taskProcessor;

  public ServerBusyHandler(ITaskProcessor taskProcessor) {
    super(); /*调用父类，默认自动释放*/
    this.taskProcessor = taskProcessor;
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, MyMessage msg) throws Exception {
    /*检查MD5*/
    String headMd5 = msg.getMsgHeader().getMd5();
    String calcMd5 = EncryptUtils.encryptObj(msg.getBody());
    if (!headMd5.equals(calcMd5)) {
      LOG.warning("报文md5检查不通过：" + headMd5 + " vs " + calcMd5 + "，关闭连接");
      ctx.writeAndFlush(buildBusyResp("报文md5检查不通过，关闭连接"));
      ctx.close();
    }
    LOG.info(msg.toString());
    if (msg.getMsgHeader().getType() == MessageType.ONE_WAY.value()) {
      LOG.info("ONE_WAY类型消息，异步处理");
      AsyncBusyProcess.submitTask(taskProcessor.execAsyncTask(msg));
    } else {
      LOG.info("TWO_WAY类型消息，应答");
      ctx.writeAndFlush(buildBusyResp("OK"));
    }
  }

  private MyMessage buildBusyResp(String result) {
    MyMessage message = new MyMessage();
    MsgHeader msgHeader = new MsgHeader();
    msgHeader.setType(MessageType.SERVICE_RESP.value());
    message.setMsgHeader(msgHeader);
    message.setBody(result);
    return message;
  }
}
